const express = require('express');
const router = express.Router();
const { query } = require('../config/database');
const { authenticateToken } = require('../middleware/auth');

// 获取激励内容
router.get('/content', authenticateToken, async (req, res) => {
  try {
    const { type } = req.query; // 'text' 或 'emoji'
    
    let sql = 'SELECT * FROM motivation_content WHERE is_active = 1';
    let params = [];
    
    if (type) {
      sql += ' AND content_type = ?';
      params.push(type);
    }
    
    sql += ' ORDER BY sort_order ASC, id ASC';
    
    const results = await query(sql, params);
    
    res.json({
      success: true,
      data: results
    });
  } catch (error) {
    console.error('获取激励内容失败:', error);
    res.status(500).json({
      success: false,
      message: '获取激励内容失败'
    });
  }
});

// 添加激励内容（管理员功能）
router.post('/content', authenticateToken, async (req, res) => {
  try {
    const { content_type, content, sort_order = 0 } = req.body;
    
    if (!content_type || !content) {
      return res.status(400).json({
        success: false,
        message: '内容类型和内容不能为空'
      });
    }
    
    if (!['text', 'emoji'].includes(content_type)) {
      return res.status(400).json({
        success: false,
        message: '内容类型必须是text或emoji'
      });
    }
    
    const sql = 'INSERT INTO motivation_content (content_type, content, sort_order) VALUES (?, ?, ?)';
    const result = await query(sql, [content_type, content, sort_order]);
    
    res.json({
      success: true,
      message: '添加成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    console.error('添加激励内容失败:', error);
    res.status(500).json({
      success: false,
      message: '添加激励内容失败'
    });
  }
});

// 更新激励内容（管理员功能）
router.put('/content/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    const { content_type, content, sort_order, is_active } = req.body;
    
    const updateFields = [];
    const updateValues = [];
    
    if (content_type !== undefined) {
      updateFields.push('content_type = ?');
      updateValues.push(content_type);
    }
    
    if (content !== undefined) {
      updateFields.push('content = ?');
      updateValues.push(content);
    }
    
    if (sort_order !== undefined) {
      updateFields.push('sort_order = ?');
      updateValues.push(sort_order);
    }
    
    if (is_active !== undefined) {
      updateFields.push('is_active = ?');
      updateValues.push(is_active);
    }
    
    if (updateFields.length === 0) {
      return res.status(400).json({
        success: false,
        message: '没有要更新的字段'
      });
    }
    
    updateValues.push(id);
    const sql = `UPDATE motivation_content SET ${updateFields.join(', ')} WHERE id = ?`;
    
    await query(sql, updateValues);
    
    res.json({
      success: true,
      message: '更新成功'
    });
  } catch (error) {
    console.error('更新激励内容失败:', error);
    res.status(500).json({
      success: false,
      message: '更新激励内容失败'
    });
  }
});

// 删除激励内容（管理员功能）
router.delete('/content/:id', authenticateToken, async (req, res) => {
  try {
    const { id } = req.params;
    
    const sql = 'DELETE FROM motivation_content WHERE id = ?';
    await query(sql, [id]);
    
    res.json({
      success: true,
      message: '删除成功'
    });
  } catch (error) {
    console.error('删除激励内容失败:', error);
    res.status(500).json({
      success: false,
      message: '删除激励内容失败'
    });
  }
});

module.exports = router;
